
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.table.AbstractTableModel;
import org.workplicity.entry.WorkSlate;
import org.workplicity.task.NetTask;
import org.workplicity.util.Helper;
import org.workplicity.worklet.WorkletContext;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Marist User
 */
public class WorkSlateTableModel extends AbstractTableModel {

    private ArrayList<WorkSlate> workSlates = new ArrayList<WorkSlate>( );
    private HashMap<Integer,WorkSlate> dirty = new HashMap<Integer,WorkSlate>( );

    private static String[] columnNames = {
        "Id",
        "Name",
        "Request ids"
    };

    @Override
    public String getColumnName(int col) {
        return columnNames[col];
    }


    public int getRowCount() {
        return workSlates.size();
    }

    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public boolean isCellEditable(int row, int col) {
        if(col == 1)
            return true;

        return false;
    }

    public Object getValueAt(int row, int col) {
        WorkSlate workSlate = workSlates.get(row);

        if(col == 0) {
            String indicator = "";

            Integer id = workSlate.getId();
            if(dirty.get(id) != null)
                indicator = "* ";
            
            return id + indicator;
        }

        if(col == 1)
            return workSlate;

        String s = "";
        for(Integer id : workSlate.getWorkRequestList())
            s += id +" ";

        return s;
    }

    @Override
    public void setValueAt(Object value, int row, int col) {
        WorkSlate workSlate = getRow(row);

        workSlate.setName((String)value);

        dirty.put(workSlate.getId(),workSlate);

        this.fireTableDataChanged();

//        WorkletContext context = WorkletContext.getInstance();
//
//        Helper.insert(workSlate, NetTask.REPOS_WORKSLATES,context);
////        getRow(row).setName((String)value);
    }

    public void refresh() {
        WorkletContext context = WorkletContext.getInstance();

        workSlates = Helper.query("WorkSlates", "/list", context);

        dirty.clear();

        this.fireTableDataChanged();
    }

    public WorkSlate getRow(int row) {
        return workSlates.get(row);
    }

    public HashMap<Integer,WorkSlate> getDirty() {
        return dirty;
    }
}
